# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render,redirect,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from projectapp.models import file_upload_data,user_messages
from projectapp.file_upload_interface import save_file1
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
# Create your views here.
import json,os,uuid,imghdr
import pandas as pd
import pickle
import requests,MySQLdb
from django.db.models import Q
from django.template.defaultfilters import stringfilter
from projectapp.templatetags.paginate_tags import paginate
from django.contrib.auth.models import User
# from django.contrib.auth.forms import UserCreationForm
from projectapp.forms import UserCreationForm
from django.contrib.auth import authenticate,login
# from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.conf import settings
from django.utils.datastructures import MultiValueDictKeyError
# import unidecode
# from unidecode import unidecode
from django.contrib.auth import views as auth_views
from django.views.decorators.csrf import csrf_exempt
db=mysql_cn= MySQLdb.connect(host='10.129.4.165',
                port=3306,user='remote', passwd='beacon',
                db='ml')
url='http://10.129.8.19:8080/'
#

def userLogout(req):
    req.session.clear()
    if hasattr(req, "member"):
        del req.member
    return HttpResponseRedirect('/')

def is_login(request):
    return 'userInfo' in request.session


def login_required(fn):
    def deco(request, *args, **kwargs):
        if not is_login(request):
            return HttpResponseRedirect("%s?returnURL=%s"%('/', request.build_absolute_uri()))
        if not hasattr(request, "member"):
            setattr(request, "member", request.session['userInfo'])
        return fn(request, *args, **kwargs)
    return deco

@csrf_exempt
def user_login(req):
    login_status = False
    if req.method=="POST":
        username = req.POST.get('name','')
        raw_password = req.POST.get('password','')
        remember_me=req.POST.get('remember_me', '')
        status=User.objects.filter(username=username).exists()
        if status:
            user = authenticate(username=username, password=raw_password)
            if user is not None and user.is_active:
                login(req,user)
                req.session['userInfo'] = {'employee_id': username}
                ms='登录成功'
                login_status=True
            else:
                ms="密码错误"
        else:
            ms='用户名错误'
        dict_content={
            'ms':ms,
            'login_status':login_status,
            'user':username,
            'ps':raw_password,
            'remember_me':remember_me,
        }
        return HttpResponse(json.dumps(dict_content), content_type="application/json")
    return render(req,'index.html')


def index(req):
    username=req.user
    login_status=False
    if str(username)!='AnonymousUser':
        login_status=True
    return render(req,'index.html',{'login_status':login_status,'user':username})
@login_required
def hd_pictures(req):
    type=req.GET.get('type')
    input = req.GET.get('input', '')
    click_input = req.GET.get('click_input', '')
    format=req.GET.get('format','')
    data = file_upload_data.objects.all().exclude(Q(name__contains='3ds')
                                                                  | Q(name__contains='max')
                                                                  | Q(name__contains='obj')
                                                                  | Q(name__contains='mtl')
                                                                  | Q(name__contains='dwg')
                                                                  | Q(name__contains='lwo')
                                                                  | Q(name__contains='vrml')
                                                                  | Q(name__contains='psd'))
    if type!='全部素材' and type!='':
        data = data.filter(type=type)
    if input!='':
        data=data.filter(Q(title__startswith=input) | Q(label__startswith=input) | Q(name__startswith=input))
    if click_input!='' and click_input!='全部':
        # data=data.filter(Q(title__startswith=click_input) | Q(label__startswith=click_input) | Q(name__startswith=click_input))
        data=data.filter(label__contains=click_input)

    if format!='' and format!='全部':
        data=data.filter(file_format__contains=format)
    data1=data.values('name','path','id')

    file_type=data.values_list('label',flat=True).distinct().order_by('label')

    file_type_1 = []
    file_type_2 = []
    for i in range(len(file_type)):
        file_type_1.append(file_type[i].split(","))
        for j in range(len(file_type_1[i])):
            file_type_2.append(file_type_1[i][j])
    file_type_2 = list(set(file_type_2))
    if click_input!='' and click_input!='全部':
        file_type_2 = [click_input]

    file_format=data.values_list('file_format',flat=True).distinct().order_by('file_format')
    object_list = list(data1)
    if req.method=="POST":
        search_type=req.POST.get('type','')
        input=req.POST.get('input','')
        if search_type=='全部素材':
            data1 = file_upload_data.objects.filter(
            Q(title__startswith=input) | Q(label__startswith=input) | Q(name__startswith=input)).exclude(
                Q(name__contains='3ds')
                | Q(name__contains='max')
                | Q(name__contains='obj')
                | Q(name__contains='mtl')
                | Q(name__contains='dwg')
                | Q(name__contains='lwo')
                | Q(name__contains='vrml')
                | Q(name__contains='psd')).values()
        else:
            data1=file_upload_data.objects.filter(Q(type=search_type)&(Q(title__startswith=input)|Q(label__startswith=input)|Q(name__startswith=input))).exclude(Q(name__contains='3ds')
                                                 |Q(name__contains='max')
                                                 |Q(name__contains='obj')
                                                 |Q(name__contains='mtl')
                                                 |Q(name__contains='dwg')
                                                 |Q(name__contains='lwo')
                                                 |Q(name__contains='vrml')
                                                 |Q(name__contains='psd')).values('name','path','id')
        file_type = data1.values_list('label', flat=True)

        file_type_1 = []
        file_type_2 = []
        for i in range(len(file_type)):
            file_type_1.append(file_type[i].split(","))
            for j in range(len(file_type_1[i])):
                file_type_2.append(file_type_1[i][j])
        file_type_2=list(set(file_type_2))
        file_format = data1.values_list('file_format', flat=True).distinct().order_by('file_format')

        object_list=list(data1)

        type=search_type
    dict_content={
        'object_list':object_list,
        'type':type,
        'url':'/ml/hd_pictures/?type=%s&'%(type),
        'input':input,
        'click_input':click_input,
        'file_type':file_type_2,
        'file_format':file_format,
        'format':format,
    }
    return render(req,'hd_pictures.html',dict_content)

@login_required
def file_upload(req):
    if req.method=="POST":
        file=req.FILES.getlist("beacon")
        title=req.POST.get('title')
        type=req.POST.get('type').replace('psd,gif,jpg,jpeg,png,gif,jpg,png,bmp','PSD素材').replace('3ds,max,mtl,obj,dwg,lwo,vrml,gif,jpg,jpeg,png,gif,jpg,png,bmp','3D模型')
        label=req.POST.get('label')
        username='cr'
        a1=save_file1(file,title,type,label,username)
        a1.get_file_upload_msg()
        a1.save_msg_to_mysql()
        dict_content = {
            'status': 'success',
            'msg': 'fff'
        }
        return HttpResponse(json.dumps(dict_content),content_type = "application/json")
    return render(req,'file_upload.html')


@login_required
def download_msg(req):
    type=req.GET.get('type')
    id=req.GET.get('id')
    msg = file_upload_data.objects.filter(id=id).values("path", "username", "img_size", "name", "img_width",
                                                        "img_height", "bf_time","same_id")
    path=url+msg[0]['path']
    pattern=msg[0]['name'].split('_')[-1].split('.')[-1]
    path1=path
    if type=="PSD素材" or type=="3D模型":
        same_id = msg[0]['same_id']
        msg1 = file_upload_data.objects.filter(same_id=same_id).exclude(id=id).values("path","name")
        path1=url+msg1[0]['path']
        pattern = msg1[0]['name'].split('_')[-1].split('.')[-1]
    dict_content={
        'data':msg,
        'path':path,
        'download_path':path1,
        'name':msg[0]['name'].split('_')[-1].split('.')[0],
        'username':msg[0]['username'],
        'time':msg[0]['bf_time'],
        'size':msg[0]['img_width']+"*"+msg[0]['img_height'],
        'pattern':pattern,
        'img_size':msg[0]['img_size'],
    }
    return render(req,'download_msg.html',dict_content)


def test(request):
    data= file_upload_data.objects.all().exclude(Q(name__contains='3ds')
                                                 |Q(name__contains='max')
                                                 |Q(name__contains='obj')
                                                 |Q(name__contains='mtl')
                                                 |Q(name__contains='dwg')
                                                 |Q(name__contains='lwo')
                                                 |Q(name__contains='vrml')
                                                 |Q(name__contains='psd')).values('name','path','id')
    object_list = list(data)
    dict_content={
        'object_list':object_list,
        'url':'/ml/test/'
    }
    return render(request,'test.html',dict_content)



@csrf_exempt
def file_upload_s(req):
    if req.method=="POST":
        data=req.FILES.get("beacon")
        a1 = {
            'success': True,
            'msg': 'upload success'
        }
        return HttpResponse(json.dumps(a1),content_type = "application/json")
    return HttpResponse('ok')


def user_registration(req):
    if req.method=="POST":
        if req.POST['type']=='first':
            user_exist_status=False
            account=req.POST.get('name','')
            user_exist = User.objects.filter(username=account).exists()
            if user_exist:
                user_exist_status = False
            else:
                user_exist_status = True
            dict_content={
                'user_exist_status':user_exist_status,
                'account':account,
            }
            return HttpResponse(json.dumps(dict_content), content_type="application/json")
        if req.POST['type']=='two':
            user_exist_status=False
            email=req.POST.get('email','')
            user_exist = User.objects.filter(email=email+"@mail.foxconn.com").exists()
            if user_exist:
                user_exist_status = False
            else:
                user_exist_status = True
            dict_content={
                'user_exist_status':user_exist_status,
                'email':email,
            }
            return HttpResponse(json.dumps(dict_content), content_type="application/json")
        if req.POST['type']=='there':
            account=req.POST.get('name','')
            password=req.POST.get('password','')
            email=req.POST.get('email','')
            try:
                user = User.objects.create_user(username=account, email=email + "@mail.foxconn.com", password=password)
                user.save()
                user = authenticate(username=account, password=password)
                login(req, user)
                submit_status=True
            except:
                submit_status=False
            dict_content={
                'submit_status':submit_status,
                'user':account,
            }
            return HttpResponse(json.dumps(dict_content), content_type="application/json")
    return HttpResponseRedirect('/ml/hd_pictures/')


